package com.leadership.api.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.leadership.api.entity.TrainerAppraisalReportSearch;
import com.leadership.api.service.ReportService;
import com.leadership.api.service.TrainingSurveyResultService;
import com.leadership.training.entity.course.Course;
import com.leadership.training.entity.project.ProjectPhaseCourse;
import com.leadership.training.entity.project.TrainingSurveyResult;
import com.leadership.training.entity.report.TrainerCourseReport;

@Component("trainerReportJob")
public class TrainerReportJob {

    private static final Logger logger = LoggerFactory.getLogger(TrainerReportJob.class);

    @Autowired
    private ReportService reportService;

    @Autowired
    private TrainingSurveyResultService trainingSurveyResultService;

    @Scheduled(cron = "0 0 18 * * ?")
    public void updateTrainerReport() {

        logger.info("#scanSurveyItems() - start at {}", new Date());

        try {

            TrainerAppraisalReportSearch trainerAppraisalReportSearch = new TrainerAppraisalReportSearch();

            int totals = reportService.count(trainerAppraisalReportSearch);
            if (totals > 0) {

                @SuppressWarnings("rawtypes")
                List courseList = reportService.searchForExport(trainerAppraisalReportSearch);
                List<TrainerCourseReport> trainerCourseReportList = new ArrayList<TrainerCourseReport>();

                TrainerCourseReport trainerCourseReport = new TrainerCourseReport();
                List<TrainerCourseReport> trainerCourseReports = new ArrayList<TrainerCourseReport>();
                for (int i = 0; i < courseList.size(); i++) {
                    ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse)courseList.get(i);
                    Course course = projectPhaseCourse.getCourse();
                    // set survey result / suggestion to each course
                    List<TrainingSurveyResult> trainingSurveyResultList =
                        trainingSurveyResultService.listByProjectPhaseCourse(projectPhaseCourse.getId());
                    // 管理类课程分类统计用
                    // 需求匹配度
                    int xu = 0;
                    int cntXu = 0;
                    // 展示技巧
                    int zsjqs = 0;
                    int cntZsjqs = 0;
                    // 改进建议
                    String gjjys = "";
                    // 内容理解深度
                    int ljsds = 0;
                    int cntLjsds = 0;
                    // 讲师总体评分
                    int zf = 0;
                    int cntDefault = 0;
                    for (int j = 0; j < trainingSurveyResultList.size(); j++) {
                        TrainingSurveyResult tsr = trainingSurveyResultList.get(j);
                        String inputVal = tsr.getInputValue();
                        if (inputVal == null || inputVal.trim().length() < 1) {
                            // empty input continue to next
                            continue;
                        }

                        if (tsr.getKeywords() != null) {
                            // check keywords
                            if (tsr.getKeywords().contains("需求匹配")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        xu += Integer.valueOf(inputVal);
                                        cntXu++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("展示技巧")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        zsjqs += Integer.valueOf(inputVal);
                                        cntZsjqs++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("内容理解深度")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        ljsds += Integer.valueOf(inputVal);
                                        cntLjsds++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("改进建议")) {
                                if (inputVal != null && inputVal.length() > 0) {
                                    if (gjjys != null && gjjys.length() > 0) {
                                        gjjys += ";";
                                    }
                                    gjjys += inputVal;
                                }
                            }

                        } else {
                            // check key words in question body

                            if (tsr.getQuestion().contains("主题课程是否满足您的期望")) {
                                // 需求匹配度
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        xu += Integer.valueOf(inputVal);
                                        cntXu++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣")) {
                                // 展示技巧
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        zsjqs += Integer.valueOf(inputVal);
                                        cntZsjqs++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("对主题内容有深度的理解")) {
                                // 内容理解深度
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        ljsds += Integer.valueOf(inputVal);
                                        cntLjsds++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("主题课程有哪些需要改进的地方")) {
                                // 改进建议
                                if (inputVal != null && inputVal.length() > 0) {
                                    if (gjjys != null && gjjys.length() > 0) {
                                        gjjys += ";";
                                    }
                                    gjjys += inputVal;
                                }
                            } else {
                                // 如果是评分值，计入总分，否则当成建议
                                try {
                                    zf += Integer.valueOf(inputVal);
                                    cntDefault++;
                                } catch (Exception e) {
                                    // not int value process as String
                                    if (inputVal != null && inputVal.length() > 0) {
                                        if (gjjys != null && gjjys.length() > 0) {
                                            gjjys += ";";
                                        }
                                        gjjys += inputVal;
                                    }
                                }
                            }
                        }
                    }
                    // 需求平均分
                    if (xu == 0 || cntXu == 0) {
                        trainerCourseReport.setPiPeiDu("0");
                    } else {
                        BigDecimal bd = new BigDecimal(xu * 1.0 / cntXu);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setPiPeiDu("" + String.valueOf(d1));
                    }
                    // 展示技巧
                    if (zsjqs == 0 || cntZsjqs == 0) {
                        trainerCourseReport.setZsjq("0");
                    } else {
                        BigDecimal bd = new BigDecimal(zsjqs * 1.0 / cntZsjqs);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setZsjq("" + String.valueOf(d1));
                    }
                    // 内容理解深度
                    if (ljsds == 0 || cntLjsds == 0) {
                        trainerCourseReport.setLjsd("0");
                    } else {
                        BigDecimal bd = new BigDecimal(ljsds * 1.0 / cntLjsds);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setLjsd("" + String.valueOf(d1));
                    }
                    // 改进建议
                    trainerCourseReport.setGjjy(gjjys);
                    // 总体评分
                    zf += xu + zsjqs + ljsds;
                    cntDefault += cntXu + cntZsjqs + cntLjsds;

                    if (zf == 0 || cntDefault == 0) {
                        trainerCourseReport.setZf("0");
                    } else {
                        BigDecimal bd = new BigDecimal(zf * 1.0 / cntDefault);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setZf("" + String.valueOf(d1));
                    }

                    // 讲师评分 =展示技巧 + 理解深度
                    if ((zsjqs + ljsds) == 0 || (cntZsjqs + cntLjsds) == 0) {
                        // 如果空值， 用总分代替
                        trainerCourseReport.setTrainerSurveyResult(trainerCourseReport.getZf());
                    } else {
                        BigDecimal bd = new BigDecimal((zsjqs + ljsds) * 1.0 / (cntZsjqs + cntLjsds));
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setTrainerSurveyResult("" + String.valueOf(d1));
                    }

                    // 课程评分（ =总分）
                    trainerCourseReport.setCourseSurveyResult(trainerCourseReport.getZf());

                    trainerCourseReports.add(new TrainerCourseReport(trainerCourseReport));

                    projectPhaseCourse.setCourse(course);
                    trainerCourseReportList
                        .add(new TrainerCourseReport(projectPhaseCourse, trainerCourseReports.get(i)));
                }

                trainingSurveyResultService.resultDataUpdate(trainerCourseReportList);

            }

        } catch (Exception e) {
            logger.error("#scanSurveyItems() - occur exception=[{}]", e);
        }

        logger.info("#scanSurveyItems() - finish at {}", new Date());
    }

}
